﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBLibrary;
using Common;
using System.Web.Security;
using System.IO;

public partial class masterPages_main_ChangeUserTypePage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void ChangeMsgButton_Click(object sender, EventArgs e)
    {
        string msg = string.Empty;
        if (!string.IsNullOrEmpty(ChangeMsgTextBox.Text))
        {
            msg += ChangeMsgTextBox.Text + Environment.NewLine;
        }
        AdminDBDetail admin = PoseidonDBHelper.AdminDB.Select<AdminDBDetail>(new DBParam("DBPre", this.Session.GetUserDBPrefix()))[0];
        msg += admin.DBPre + Environment.NewLine;
        msg += admin.AdminName + Environment.NewLine;
        msg += admin.KeyId + Environment.NewLine;
        EMailHelper.SendEmail(msg);
        this.Response.Redirect("~/Default.aspx");
    }

    protected void CommitButton_Click(object sender, EventArgs e)
    {
        string newKeyFileId = string.Empty;
        using (Stream stream = KeyFileUpload.FileContent)
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                newKeyFileId = reader.ReadToEnd();
            }
        }
        DB db = PoseidonDBHelper.AdminDB;
        List<KeyDetail> ks = db.Select<KeyDetail>(new DBParam("KeyId", newKeyFileId));
        if (ks != null && ks.Count > 0)
        {
            KeyDetail newKd = ks[0];
            KeyDetail currentKd = db.Select<KeyDetail>(new DBParam("DBPre", this.Session.GetUserDBPrefix()))[0];
            AdminDBDetail admin = db.Select<AdminDBDetail>(new DBParam("DBPre", currentKd.DBPre))[0];
            admin.KeyId = newKd.KeyId;
            newKd.DBPre = currentKd.DBPre;
            newKd.IsInUse = true;
            currentKd.IsInUse = false;
            db.Update(admin, "AdminName");
            db.Update(newKd, "KeyId");
            db.Update(currentKd, "KeyId");
        }
        FormsAuthentication.SignOut();
    }
}